﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SkypeTranslater.Windows
{
	/// <summary>
	/// Interaction logic for MailWindow.xaml
	/// </summary>
	public partial class MailWindow
	{
		public List<OutlookManagerLibrary.OutlookMailInfo> MailItems
		{
			get { return (List<OutlookManagerLibrary.OutlookMailInfo>)GetValue(MailItemsProperty); }
			set { SetValue(MailItemsProperty, value); }
		}

		// Using a DependencyProperty as the backing store for MailItems.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty MailItemsProperty =
			DependencyProperty.Register("MailItems", typeof(List<OutlookManagerLibrary.OutlookMailInfo>), typeof(MailWindow), new UIPropertyMetadata(null));


		public List<string> Folders
		{
			get { return (List<string>)GetValue(FoldersProperty); }
			set { SetValue(FoldersProperty, value); }
		}

		// Using a DependencyProperty as the backing store for Folders.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty FoldersProperty =
			DependencyProperty.Register("Folders", typeof(List<string>), typeof(MailWindow), new UIPropertyMetadata(null));


		public int UnreadCount
		{
			get { return (int)GetValue(UnreadCountProperty); }
			set { SetValue(UnreadCountProperty, value); }
		}

		// Using a DependencyProperty as the backing store for UnreadCount.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty UnreadCountProperty =
			DependencyProperty.Register("UnreadCount", typeof(int), typeof(MailWindow), new UIPropertyMetadata(null));


		private OutlookManagerLibrary.OutlookManager m_outlookManager = null;

		public MailWindow()
		{
			InitializeComponent();
			this.Closing += new System.ComponentModel.CancelEventHandler(MailWindow_Closing);
		}

		internal void InitializeOutlookManager(OutlookManagerLibrary.OutlookManager manager)
		{
			if (manager == null)
				throw new ArgumentNullException("manager");
			m_outlookManager = manager;
		}

		void MailWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			e.Cancel = false;
			MailItems = null;
			Folders = null;
			if (m_outlookManager != null)
				m_outlookManager = null;
			GC.Collect(0);
			if (this.Owner != null)
				Owner.Activate();
		}

		private void cmbFolders_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			string folderName = cmbFolders.SelectedItem as string;

			if (!string.IsNullOrEmpty(folderName))
			{
				WeakReference WeakRef = null;
				System.Threading.Tasks.Task listTask = new System.Threading.Tasks.Task(new Action(() =>
					{
						this.Dispatcher.BeginInvoke(new Action(() =>
							{
								MailItems = null;
								dataGridMails.Visibility = System.Windows.Visibility.Collapsed;
								busyIndicator.Visibility = System.Windows.Visibility.Visible;
								busyIndicator.IsBusy = true;
							}), System.Windows.Threading.DispatcherPriority.Send);

						WeakRef = new WeakReference(m_outlookManager.GetEmailListFromFolder(folderName));
					}));

				listTask.Start();

				listTask.ContinueWith(prevTask =>
					{
						MailItems = null;
						MailItems = WeakRef.Target as List<OutlookManagerLibrary.OutlookMailInfo>;
						prevTask.Dispose();
						busyIndicator.Visibility = System.Windows.Visibility.Collapsed;
						busyIndicator.IsBusy = false;
						dataGridMails.Visibility = System.Windows.Visibility.Visible;
					}, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskContinuationOptions.OnlyOnRanToCompletion,
					System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());

				listTask.ContinueWith(prevTask =>
					{
						App.Log.Error("Error occurred while trying retrieve emails", prevTask.Exception);
						prevTask.Dispose();
						busyIndicator.Visibility = System.Windows.Visibility.Collapsed;
						busyIndicator.IsBusy = false;
						dataGridMails.Visibility = System.Windows.Visibility.Visible;

					}, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskContinuationOptions.OnlyOnRanToCompletion,
					System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());


			}
		}

		private void dataGridMails_MouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
			IInputElement element = e.MouseDevice.DirectlyOver;
			if (element != null && element is FrameworkElement)
			{
				if (((FrameworkElement)element).Parent is DataGridCell)
				{
					var grid = sender as DataGrid;
					if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
					{
						string EntryId = (grid.SelectedItems[0] as OutlookManagerLibrary.OutlookMailInfo).EntryID;
						if (!string.IsNullOrEmpty(EntryId)
							&&
							(MessageBox.Show(this, "Do you want to translate this email?", "Confirm translation", MessageBoxButton.YesNo, MessageBoxImage.Question)
							== MessageBoxResult.Yes)
						)
						{
							Windows.TranslateMailWindow wind = new TranslateMailWindow();
							wind.Owner = this;
							wind.ShowInTaskbar = false;
							if (dataGridMails.SelectedItem != null)
							{
								wind.OriginalText = (dataGridMails.SelectedItem as OutlookManagerLibrary.OutlookMailInfo).Body;
							}
							wind.ShowDialog();
						}


					}
				}
			}
			e.Handled = true;
		}
	}
}
